package com.iexbuy.ihg.ui.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.adapter.ViewPagerAdapter;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.common.ExtraKeyConstant;
import com.iexbuy.ihg.entity.UserObjectResponse;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.ui.fragment.LoginFragment;
import com.iexbuy.ihg.ui.view.WaterWave;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.ToastUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

public class StartActivity extends Activity implements View.OnClickListener, ViewPager.OnPageChangeListener {

	
	@ViewInject(R.id.rootView)
	private RelativeLayout rootView;
	@ViewInject(R.id.versionName)
	private TextView versionName;
	@ViewInject(R.id.loginBtn)
	private Button loginBtn;

	private ViewPager vp;
	private ViewPagerAdapter vpAdapter;
	private List<View> views;

	//引导图片资源
	private static final int[] pics = { R.drawable.guid_01, R.drawable.guid_1, R.drawable.guid_2};

	//底部小店图片
	private ImageView[] dots ;

	//记录当前选中位置
	private int currentIndex;

	private boolean isShowingLoginBtn = true;
	
	private StartTask startTask;
	
	protected ProgressDialog mDialog;
	
	private static StartActivity instance;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.start_activity);
		ViewUtils.inject(this);
		
		instance = this;
		
		String testInfoString = App.test ? "测试版本不连后台" : "";
		if (ServiceHelper.SERVER_ROOT.contains(":8081")) {
			testInfoString = "测试环境";
		}
		versionName.setText(App.sAPKVersionName + " " + testInfoString);
		
		startTask = new StartTask();
//		startTask.execute();
		
		MobclickAgent.updateOnlineConfig(this);

		//如果已显示过指引页面，直接跳转到登录或主界面
		if (App.sPreferences.isShowGuidPage()) {
			onLoginClick(null);
		} else {
			views = new ArrayList<View>();

			LinearLayout.LayoutParams mParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.MATCH_PARENT);

			//初始化引导图片列表
			for(int i=0; i<pics.length; i++) {
				ImageView iv = new ImageView(this);
				iv.setLayoutParams(mParams);
				iv.setImageResource(pics[i]);
				iv.setScaleType(ImageView.ScaleType.FIT_XY);
				views.add(iv);
			}
			vp = (ViewPager) findViewById(R.id.viewpager);
			//初始化Adapter
			vpAdapter = new ViewPagerAdapter(views);
			vp.setAdapter(vpAdapter);
			//绑定回调
			vp.setOnPageChangeListener(this);

			//初始化底部小点
			initDots();

			App.sPreferences.setIsShowGuidPage(true);
		}
	}

	private void initDots() {
		LinearLayout ll = (LinearLayout) findViewById(R.id.ll);

		dots = new ImageView[pics.length];

		//循环取得小点图片
		for (int i = 0; i < pics.length; i++) {
			dots[i] = (ImageView) ll.getChildAt(i);
			dots[i].setEnabled(true);//都设为灰色
			dots[i].setOnClickListener(this);
			dots[i].setTag(i);//设置位置tag，方便取出与当前位置对应
		}

		currentIndex = 0;
		dots[currentIndex].setEnabled(false);//设置为白色，即选中状态
	}

	/**
	 *设置当前的引导页
	 */
	private void setCurView(int position) {
		if (position < 0 || position >= pics.length) {
			return;
		}
		vp.setCurrentItem(position);
	}

	/**
	 *这只当前引导小点的选中
	 */
	private void setCurDot(int positon) {
		if (positon < 0 || positon > pics.length - 1 || currentIndex == positon) {
			return;
		}

		dots[positon].setEnabled(false);
		dots[currentIndex].setEnabled(true);
		currentIndex = positon;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		JPushInterface.onResume(this);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		JPushInterface.onPause(this);
	}
	
	@OnClick({R.id.loginBtn})
	private void onLoginClick(View view) {
		if (App.sPreferences.isLoginIn()) {
			//如果已登录，自动跳转到主页面
			startActivity(new Intent(StartActivity.this, MainTabActivity.class));
		} else {
			//如果未登录，但有保存用户名和密码，自动登录
			if (TextUtils.isEmpty(App.sPreferences.getUserName()) ||  TextUtils.isEmpty(App.sPreferences.getPsw())) {
				Intent intent = new Intent(this, SingleFragmentActivity.class);
				intent.putExtra(ExtraKeyConstant.KEY_FRAGMENT, LoginFragment.class);
				intent.putExtra(ExtraKeyConstant.KEY_FINISH_ACTIVITY, true);
				startActivity(intent);
			} else {
				login(App.sPreferences.getUserName(), App.sPreferences.getPsw());
			}
		}
		StartActivity.this.finish();
	}

	@Override
	public void onClick(View view) {
		int position = (Integer)view.getTag();
		setCurView(position);
		setCurDot(position);
	}

	@Override
	public void onPageScrolled(int i, float v, int i1) {

	}

	@Override
	public void onPageSelected(int i) {
		setCurDot(i);
		if (i == (pics.length-1)) {
			loginBtn.setVisibility(View.VISIBLE);
		} else {
			loginBtn.setVisibility(View.GONE);
		}
	}

	@Override
	public void onPageScrollStateChanged(int i) {

	}

	private class StartTask extends AsyncTask<Void, String, String>{

		@Override
		protected String doInBackground(Void... params) {
			try {
				Thread.sleep(2000);
				App.sContext.init();
				String version = "";
				
				PackageManager packageManager = getPackageManager();
		        PackageInfo packInfo =  packageManager.getPackageInfo(getPackageName(),0);
				version = packInfo.versionName;
				
				if (App.sPreferences.isLoginIn()) {
					//login(App.sPreferences.getUserName(), App.sPreferences.getPsw());//自动登录
				}


				
				return null;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		
	}
	
	private void login(final String username, final String passwordMd5) {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("username", username);
		paramMap.put("pwd", passwordMd5);

		ServiceHelper.send(StartActivity.this, ServiceHelper.LOGIN, paramMap,
	        new RequestCallBack<String>() {
        		@Override
	        	public void onStart() {
        			StartActivity.this.showDialog("登录中...");
	            }
        		@Override
        		public void onCancelled() {
        			StartActivity.this.closeDialog();
        	    }
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					StartActivity.this.closeDialog();
					ToastUtils.toast(StartActivity.this, "登录成功。");
					String responseString = responseInfo.result;
					Log.i("", responseString);
//					CurrentLoginUserResponse userIdInfo  = JsonUtils.parseJsonStrToObject(responseString, CurrentLoginUserResponse.class);
//					App.sPreferences.setUserName(username);
//					App.sPreferences.setName(userInfo.getUser().getName());
//					App.sPreferences.setPsw(passwordMd5);
//					App.sPreferences.setUserId(userInfo.getUser().getUserId());
//					App.sPreferences.setToken(userInfo.getToken());
//					App.sPreferences.setLoginIn(true);
					UserObjectResponse userInfo = JsonUtils.parseJsonStrToObject(responseString, UserObjectResponse.class);
					App.sPreferences.setUserName(username);
					App.sPreferences.setName(userInfo.getBody().getName());
					App.sPreferences.setPsw(passwordMd5);
					App.sPreferences.setUserId(userInfo.getBody().getId());
					App.sPreferences.setLoginIn(true);
					
					startActivity(new Intent(StartActivity.this, MainTabActivity.class));
					StartActivity.this.finish();
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					StartActivity.this.closeDialog();
					if (msg.contains("apache.http.conn")) {
						CommUtil.showAlert(StartActivity.this, "登录失败", "连接不上服务器", null);
					} else {
						CommUtil.showAlert(StartActivity.this, "登录失败", "用户名或密码不对", null);
					}
					
				}
	    });
	}
	
	public void showDialog(String text){
		mDialog = ProgressDialog.show(this, null, text);  
		mDialog.setCanceledOnTouchOutside(false);
		mDialog.setIndeterminate(true);
		mDialog.setCancelable(true);
	}
	
	public void closeDialog(){
		try {
			if (mDialog != null)
				mDialog.dismiss();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @return the instance
	 */
	public static StartActivity getInstance() {
		return instance;
	}
}
